package com.android.lovely.ui.fragment

import androidx.core.os.bundleOf
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.whenResumed
import com.android.lovely.api.service.userService
import com.android.lovely.const.HomeSelect
import com.android.lovely.data.LovelyTask
import com.android.lovely.data.shareInfo
import com.android.lovely.databinding.FragmentLovelyTaskBinding
import com.android.lovely.ext.init
import com.android.lovely.ext.share
import com.android.lovely.framework.BaseFragment
import com.android.lovely.framework.UIController.dismissLoading
import com.android.lovely.ui.activity.InviteActivity
import com.android.lovely.ui.activity.PayActivity
import com.android.lovely.ui.adapter.TaskAdapter
import com.android.lovely.ui.dialog.CodeDialog
import com.android.lovely.ui.dialog.PayDialog
import com.android.lovely.ui.dialog.SignDialog
import com.android.lovely.ui.dialog.StarDialog
import com.android.lovely.user.UserManager
import com.kotlin.extensions.bus.FlowBus
import com.kotlin.extensions.bus.post
import com.kotlin.extensions.context.ContextExt.startPage
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay

class TaskFragment : BaseFragment<FragmentLovelyTaskBinding>(), (LovelyTask?, Int) -> Unit {

    private var job: Job? = null

    private val adapter by lazy { TaskAdapter(lifecycleScope) }

    override fun initView() {
        mBinding.tasks.adapter = adapter
        adapter.onItemClick = this
        mBinding.srlRefresh.init()
        mBinding.srlRefresh.setOnRefreshListener { refreshTask() }
        refreshTask()
    }

    override suspend fun initData() {

    }

    private fun refreshTask() {
        if (job?.isActive == true) return
        mBinding.srlRefresh.isRefreshing = true
        job = lifecycleScope.launchSafety {
            val result = userService.getTaskList()
            adapter.updateList(result)
        }.onComplete {
            mBinding.srlRefresh.isRefreshing = false
        }
    }

    override fun invoke(item: LovelyTask?, position: Int) {
        item ?: return
        when (item.type) {
            "sign_in" -> startPage<SignDialog>()
            "ad_buy_page" -> startPage<PayActivity>()
            "ad_normal" -> PayDialog().show(childFragmentManager)
            "ad_chat_page" -> FlowBus.post(HomeSelect(1))
            "share" -> share()
            "evaluation" -> rateApp()
            "invite" -> {
                val code = shareInfo?.inviteCode
                val content = shareInfo?.shareContent
                if (code.isNullOrEmpty() || content.isNullOrEmpty()) return
                startPage<InviteActivity>("code" to code, "share_content" to content)
            }

            "enter_code" -> {
                val code = shareInfo?.inviteUserCode.orEmpty()
                CodeDialog().apply {
                    arguments = bundleOf("code" to code)
                    onInputCode = {
                        refreshTask()
                    }
                }.show(childFragmentManager)
            }
        }
    }

    private fun rateApp() {
        StarDialog(requireContext()).also {
            it.onStar = {
                viewLifecycleOwner.lifecycleScope.launchSafety {
                    userService.getReward(mapOf("ad_type" to "evaluation", "param" to it.toString()))
                    refreshTask()
                    UserManager.refreshAuth()
                }
            }
        }.show()
    }

    private fun share() {
        shareInfo?.shareContent?.share()
        shareInfo ?: return
        viewLifecycleOwner.lifecycleScope.launchSafety {
            delay(1000)
            whenResumed {
                runCatching {
                    userService.getReward(mapOf("ad_type" to "share"))
                    UserManager.refreshAuth()
                    refreshTask()
                }
            }
        }
    }
}